import { useEffect, useState } from 'react';
import style from './index.module.scss';
import { BaseUrl } from '@/utils/index';
import { goUserPage, showToast } from './util';
import Gift from './gift';

import desc1 from '@/assets/images/christmas/desc1.png';
import desc2 from '@/assets/images/christmas/desc2.png';
import Icon1 from '@/assets/images/christmas/1.png';
import Icon2 from '@/assets/images/christmas/2.png';
import Icon3 from '@/assets/images/christmas/3.png';

const Content = () => {
    const urlParams = new URLSearchParams(window.location.search);
    const authorizationToken = urlParams.get('userId');

    // 1送 2收 3找
    const [type, setType] = useState(1); // 类型 1送 2收 3找
    const [data, setData] = useState([]); // 排行榜数据
    const [info, setInfo] = useState(); // 当前用户信息

    const getRank = async () => {
        let url;
        switch (type) {
            case 1:
                url = `/gift/rank/send/bell/rank`;
                break;
            case 2:
                url = `/gift/rank/receive/bell/rank`;
                break;
            case 3:
                url = `/gift/rank/find/hat/rank`;
                break;
        }
        fetch(BaseUrl + url, {
            method: 'GET',
            headers: {
                Authorization: authorizationToken,
            },
        })
            .then((response) => response.json())
            .then((response) => {
                if (response.code === 200 && response.data) {
                    setData(response.data.list || []);
                    setInfo(response.data.myRank);
                } else {
                    setData([]);
                    console.error(
                        'Failed to fetch ranking data:',
                        response.msg
                    );
                    showToast(response.msg);
                }
            })
            .catch((error) =>
                console.error('Error fetching ranking data:', error)
            );
    };

    const fetchSubscribe = async (item, url) => {
        fetch(BaseUrl + url, {
            method: 'POST',
            headers: {
                Authorization: authorizationToken,
                'content-type': 'application/json',
            },
            body: JSON.stringify({
                targetUserId: item.userId,
                userId: info.userId,
            }),
        })
            .then((response) => response.json())
            .then((response) => {
                if (response.code === 200 && response.data) {
                    console.log('成功');
                    getRank();
                } else {
                    console.error(
                        'Failed to fetch ranking data:',
                        response.msg
                    );
                    showToast(response.msg);
                }
            })
            .catch((error) =>
                console.error('Error fetching ranking data:', error)
            );
    };

    const clickSubscribe = async (item) => {
        if (item.userId === info?.userId) {
            // 禁止关注自己
            return;
        }
        if (item.relation === 2 || item.relation === 3) {
            fetchSubscribe(item, `/user/friend/subscribe`); // 去关注
        } else if (item.relation === 1 || item.relation === 4) {
            fetchSubscribe(item, `/user/friend/unsubscribe`); // 取消关注
        }
    };

    useEffect(() => {
        if (authorizationToken) {
            getRank();
        } else {
            console.error('Authorization token not found in URL');
        }
    }, [type]);

    return (
        <>
            <div className={style.content_wrap}>
                <div className={style.descBox}>
                    <Gift />
                    <img className={style.desc1} src={desc1} alt="图" />
                    <img src={desc2} alt="图" />
                </div>
                <div className={style.rank_container}>
                    <div className={style.btn_box}>
                        <div
                            className={`${style.btn_switch}  ${
                                type === 1 ? '' : style.no_select
                            }`}
                            onClick={() => setType(1)}
                        >
                            送铃铛
                        </div>
                        <div
                            className={`${style.btn_switch} ${
                                type === 2 ? '' : style.no_select
                            } `}
                            onClick={() => setType(2)}
                        >
                            收铃铛
                        </div>
                        <div
                            className={`${style.btn_switch} ${
                                type === 3 ? '' : style.no_select
                            } `}
                            onClick={() => setType(3)}
                        >
                            找帽子
                        </div>
                    </div>
                    <div className={style.rank_box}>
                        <div className={style.rank_list}>
                            {data.map((item, i) => (
                                <div
                                    className={style.td_box}
                                    key={item?.userId}
                                >
                                    {i === 0 && (
                                        <div className={style.rank}>
                                            <img src={Icon1} alt=""></img>
                                            <span>1</span>
                                        </div>
                                    )}
                                    {i === 1 && (
                                        <div className={style.rank}>
                                            <img src={Icon2} alt=""></img>
                                            <span>2</span>
                                        </div>
                                    )}
                                    {i === 2 && (
                                        <div className={style.rank}>
                                            <img src={Icon3} alt=""></img>
                                            <span>3</span>
                                        </div>
                                    )}
                                    {i > 2 && (
                                        <div className={style.rank}>
                                            {i >= 99 ? '99+' : i + 1}
                                        </div>
                                    )}
                                    <div className={style.user}>
                                        <img
                                            src={item?.avatar}
                                            alt=""
                                            onClick={() =>
                                                goUserPage(item.userId)
                                            }
                                        />
                                        <div>
                                            <div className={style.nickname}>
                                                {item.nickname || item.account}
                                            </div>
                                            <div className={style.score}>
                                                {type === 3
                                                    ? '帽子值'
                                                    : '铃铛数'}
                                                ：{item?.showValue}
                                            </div>
                                        </div>
                                    </div>
                                    <div
                                        className={
                                            item.relation === 1 ||
                                            item.relation === 4
                                                ? style.rankBtn_blue
                                                : style.rankBtn
                                        }
                                        onClick={() => clickSubscribe(item)}
                                        style={{
                                            opacity:
                                                item.relation < 5 &&
                                                item.userId !== info?.userId
                                                    ? 1
                                                    : 0.6,
                                        }}
                                    >
                                        {item.relation === 1 && '已关注'}
                                        {item.relation === 2 && '回关+'}
                                        {item.relation === 3 && '关注+'}
                                        {item.relation === 4 && '已互关'}
                                        {item.relation === 5 && '关注+'}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>

                    <div className={`${style.user_box}`}>
                        <div className={style.user_content}>
                            <div className={style.left}>
                                <div className={style.my_rank_desc}>
                                    我的排名
                                </div>
                                <div className={style.my_rank_index}>
                                    {info?.rank || '未上榜'}
                                </div>
                            </div>
                            <div className={style.user}>
                                <img src={info?.avatar} alt="" />
                                <span>
                                    {info?.nickname ||
                                        info?.account ||
                                        '我的昵称'}
                                </span>
                            </div>
                            <div className={style.right}>
                                <div className={style.my_rank_desc}>
                                    {type === 3 ? '帽子数' : '铃铛值'}
                                </div>
                                <div className={style.my_rank_num}>
                                    {info?.showValue || 0}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
};

export default Content;
